import React, {Component} from 'react';
import {ActivityIndicator, FlatList, RefreshControl, StyleSheet, Text, View} from 'react-native';
import PropTypes from 'prop-types'

// RefreshList.propTypes = {
//     getRequest: PropTypes.func,
//     initialData:PropTypes.array,
//     requestSuccess:PropTypes.func,
//     requestError:PropTypes.func
// }

export default class RefreshList extends Component {



    constructor(props){
        super(props);
        console.log('refresh list props:',props);
        this.state = {
            page:1,
            dataArray:props.initialData,
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            isRefreshing:false,//下拉控制
        };
        this.fetchData = this.fetchData.bind(this)

    }

    //组件挂载完成后执行的方法
    componentDidMount(){

    }



    shouldComponentUpdate() {
        return true
    }

    fetchData = ()=>{
        const request = this.props.getRequest(this.state.page)

        request.then(res=>{
            console.log('refresh fetchData:---',res);
            this.props.requestSuccess(res,(data)=>{
                const {list,totalPage} = data
                let foot = 0;
                if(this.state.page>=totalPage){
                    foot = 1;//listView底部显示没有更多数据了
                }

                this.setState({
                    //复制数据源
                    dataArray:this.state.dataArray.concat(list),

                    showFoot:foot,
                    isRefreshing:false,
                });
            })

        }).catch((error)=>{
            this.props.requestError(error)
            this.setState({
                error: true,
                errorInfo: error
            });
        })
    }

    handleRefresh = () => {
        this.setState({
            page:1,
            isRefreshing:true,//tag,下拉刷新中，加载完全，就设置成flase
            dataArray:[]
        });
        this.fetchData()

    }


    _keyExtractor = (item, index) => index;


    render() {

        return (
            <FlatList
                data={this.state.dataArray}
                renderItem={this.props.renderItem}
                ListFooterComponent={this._renderFooter.bind(this)}
                onEndReached={this._onEndReached.bind(this)}
                onEndReachedThreshold={0.1}
                ItemSeparatorComponent={this._separator}
                keyExtractor={this._keyExtractor}
                windowSize={300}
                //为刷新设置颜色
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.isRefreshing}
                        onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
                        colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}
                        progressBackgroundColor="#ffffff"
                    />
                }
            />
        );
    }



    _separator(){
        return <View style={{height:1,backgroundColor:'#999999'}}/>;
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.page!=1) && (this.state.page>=totalPage)){
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据，在componentDidMount()已经请求过数据了
        if (this.state.page>1){
            this.fetchData();
        }
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    center:{
        justifyContent:'center',alignItems: 'center'
    },
    oneBtn: {
        padding: 5,
        borderRadius: 5,
    },
    oneBox: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    footer:{
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingVertical:10
    }
});
